package com.zhanghe.study.springmvc.controller.exception;

import com.zhanghe.study.springmvc.dto.User;
import com.zhanghe.study.springmvc.exception.BusinessException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 异常处理测试
 * @author zh
 * @date 2021/1/9 18:06
 */
@Controller
@RequestMapping("/exception")
public class ExceptionController {

    // 使用@ExceptionHandler只对该@Controller有效，对其他Controller无效，如果想要对所有Controller生效，
    // 需要将该方法写到基类，让所有的Controller都继承该基类Controller
    @ExceptionHandler(BusinessException.class)
    @ResponseBody
    public String exception(Exception e){
        return "出现异常"+e.getMessage();
    }

    @RequestMapping("/testException")
    @ResponseBody
    public String testException(){
        User user = null;
        System.out.println(user.getId());
        return "success";
    }

    @RequestMapping("/testBusinessException")
    @ResponseBody
    public String testBusinessException(){
        throw new BusinessException();
    }
}
